package dilmaj.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

import dilmaj.shared.AreaVO;
import dilmaj.shared.TermVO;

import java.util.*;

public class AddAreasPanel extends PopupPanel {
	ArrayList<AreaVO> allAreas=new ArrayList<AreaVO>();
	VerticalPanel mainPanel=new VerticalPanel();
	ArrayList<AreaVO> selectedAreas=new ArrayList<AreaVO>();
	TermVO termVO;
	TermServiceAsync termSvc = GWT.create(TermService.class);
	boolean viewOnly;

	public AddAreasPanel(ArrayList<AreaVO> inputAreas, TermVO termVO, boolean viewOnly) {
		allAreas.addAll(inputAreas);
		
		this.viewOnly=viewOnly;
		
		Iterator iterator=allAreas.iterator();
		while (iterator.hasNext()) {
			AreaVO currentArea=(AreaVO)iterator.next();
			CheckBox currentBox=new CheckBox(currentArea.getCaption());
			currentBox.addClickHandler(new CheckHandler());
			mainPanel.add(currentBox);
			
			if (termVO.getAreas().contains(currentArea.getId())) {
				selectedAreas.add(currentArea);
				currentBox.setValue(true);
			}
			
			currentBox.setEnabled(!viewOnly);
		}
		
		this.termVO=termVO;
		
		Button closeButton=new Button("Close");
		CloseHandler closeHandler=new CloseHandler(this);
		closeButton.addClickHandler(closeHandler);
		mainPanel.add(closeButton);
				
		add(mainPanel);
	}
	
	class CheckHandler implements ClickHandler {
		public void onClick(ClickEvent event) {
			Iterator iterator=allAreas.iterator();
			while (iterator.hasNext()) {
				AreaVO currentArea=(AreaVO)iterator.next();
				CheckBox currentBox=(CheckBox)event.getSource();
				
				if (currentArea.getCaption().compareTo(currentBox.getText())==0) {
					if (currentBox.getValue())
						selectedAreas.add(currentArea);
					else
						selectedAreas.remove(currentArea);
				}
			}
		}
	}
	
	class CloseHandler implements ClickHandler {
		private AddAreasPanel owner;
		
		public CloseHandler(AddAreasPanel owner) {
			this.owner=owner;
		}
		
		public void onClick(ClickEvent event) {
			termVO.setAreas(selectedAreas);

		    if (termSvc == null) {
			      termSvc = GWT.create(TermService.class);
		    }
		    termSvc.update(termVO, updateCallback);
		    
			owner.hide();
		}
	}
	
	  AsyncCallback<TermVO> updateCallback = new AsyncCallback<TermVO>() {
		  public void onFailure(Throwable caught) {
		        // TODO: Do something with errors.
		  }
	
		  public void onSuccess(TermVO result) {
		  }
	  };

}
